/* eslint-disable */
import CryptoJS from 'crypto-js'
// eslint-disable-next-line
import Bus from 'assets/utils/bus'
import Qs from 'qs'

// DES加密
export var encryptByDES = {
  ECB: function(message, key) {
    var keyHex = CryptoJS.enc.Utf8.parse(key)
    var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    })
    return encrypted.ciphertext.toString().toLowerCase()
  },
  CBC: function(message, key) {
    var keyHex = CryptoJS.enc.Utf8.parse(key)
    var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
      iv: keyHex,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    })
    return encrypted.ciphertext.toString().toLowerCase()
  }
}

export var decryptByDES = {
  ECB: function(ciphertext, key) {
    var keyHex = CryptoJS.enc.Utf8.parse(key)
    var decrypted = CryptoJS.DES.decrypt({
      ciphertext: CryptoJS.enc.Hex.parse(ciphertext.toLowerCase())
    }, keyHex, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    })
    return decrypted.toString(CryptoJS.enc.Utf8)
  },
  CBC: function(ciphertext, key) {
    var keyHex = CryptoJS.enc.Utf8.parse(key)
    var decrypted = CryptoJS.DES.decrypt({
      ciphertext: CryptoJS.enc.Hex.parse(ciphertext.toLowerCase())
    }, keyHex, {
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
      iv: keyHex
    })
    return decrypted.toString(CryptoJS.enc.Utf8)
  }
}

// md5
export function encryptByMd5(str) {
  return CryptoJS.MD5(str).toString()
}

export function isWechat() {
  return /micromessenger/i.test(window.navigator.userAgent + window.navigator.platform)
}
export function isIOS() {
  return /iphone|ipad|ipod/i.test(window.navigator.userAgent + window.navigator.platform)
}
export function isAndroid() {
  return /android|linux/i.test(window.navigator.userAgent + window.navigator.platform)
}
export function isWeibo() {
  return /weibo/i.test(window.navigator.userAgent + window.navigator.platform)
}
export function isQQ() {
  return /qq/i.test(window.navigator.userAgent + window.navigator.platform)
}

// 基础路径baseUrl，自适应预发布pretest_dzg和普通环境
export const baseUrl = /pretest_product-shelves-as/.test(window.location.href) ? '/pretest_product-shelves-as' : '/product-shelves-as'

// 获取url地址中的参数
export function getParamValue(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) return (r[2])
  return null
}

// 获取时间戳
export function getTimeStamp() {
  var now = new Date()
  var year = '' + now.getFullYear()
  var month = now.getMonth() + 1 < 10 ? ('0' + (now.getMonth() + 1)) : ('' + (now.getMonth() + 1))
  var day = now.getDate() < 10 ? ('0' + now.getDate()) : ('' + now.getDate())
  var hour = now.getHours() < 10 ? ('0' + now.getHours()) : ('' + now.getHours())
  var minute = now.getMinutes() < 10 ? ('0' + now.getMinutes()) : ('' + now.getMinutes())
  var second = now.getSeconds() < 10 ? ('0' + now.getSeconds()) : ('' + now.getSeconds())
  return year + month + day + hour + minute + second
}

/**
* 日期格式化
* 例：dateFormat(new Date(), "YYYY/MM/DD hh:mm:ss S");
* 支持格式YYYY,yyyy; MM; DD,dd; HH,hh; mm; ss, S(毫秒)
*/
export function dateFormat(date, fmt) {
  if (!(date instanceof Date)) date = new Date(date)
  var o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds() // 毫秒
  }
  if (/(y+)/i.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (var k in o) {
    if ((['d+', 'h+'].indexOf(k) === -1 ? new RegExp('(' + k + ')') : new RegExp('(' + k + ')', 'i')).test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
  }
  return fmt
}

/**
 * 设置cookie值
 * @param c_name
 * @param value
 * @param expiredays
 * @returns
 */
export var setCookie = function(c_name, value, expiredays = 30) {
  var expires = ''
  if (expiredays && expiredays > 0) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    expires = exdate.toGMTString()
  }
  var encryptValue = encryptByDES.CBC(JSON.stringify(value), 'pspc-cookie')
  if (expires) {
    document.cookie = c_name + '=' + encryptValue + ';expires=' + expires
  } else {
    document.cookie = c_name + '=' + encryptValue
  }
}
/**
 * 从cookie取值
 * @param c_name
 * @returns
 */
export var getCookie = function(c_name) {
  var mycookie = document.cookie
  if (c_name && mycookie && mycookie.length > 0) {
    var c_start = mycookie.indexOf(c_name + '=')
    if (c_start !== -1) {
      c_start = c_start + c_name.length + 1
      var c_end = mycookie.indexOf(';', c_start)
      if (c_end === -1) {
        c_end = mycookie.length
      }
      var decryptStr = decryptByDES.CBC(mycookie.substring(c_start, c_end), 'pspc-cookie')
      var result = decryptStr.replace(/^"|"$/g, '').replace(/\\/g, '') || ''
      try {
        result = JSON.parse(result)
      } catch (e) {
        return result
      }
      return result
    }
  }
  return ''
}
/*
* 用于存储本地信息
*/
export function saveStorage(name, value) {
  var encryptValue = encryptByDES.CBC(JSON.stringify(value), 'pspc-storage')
  window.localStorage.setItem(name, encryptValue)
}

/*
* 用于读取本地信息
*/
export function getStorage(name) {
  var encryptStr = window.localStorage.getItem(name)
  if (encryptStr) {
    encryptStr = decryptByDES.CBC(encryptStr, 'pspc-storage')
    var result = encryptStr.replace(/^"|"$/g, '').replace(/\\/g, '') || ''
    try {
      result = JSON.parse(result)
    } catch (e) {
      return result
    }
    return result
  }
  return ''
}

/*
* 用于删除本地信息
*/
export function removeStorage(name) {
  window.localStorage.removeItem(name)
}

/*
* 用于存储session信息
*/
export function saveSession(name, value) {
  var encryptValue = encryptByDES.CBC(JSON.stringify(value), 'pspc-session')
  window.sessionStorage.setItem(name, encryptValue)
}

/*
* 用于读取session信息
*/
export function getSession(name) {
  var encryptStr = window.sessionStorage.getItem(name)
  if (encryptStr) {
    encryptStr = decryptByDES.CBC(encryptStr, 'pspc-session')
    var result = encryptStr.replace(/^"|"$/g, '').replace(/\\/g, '') || ''
    try {
      result = JSON.parse(result)
    } catch (e) {
      return result
    }
    return result
  }
  return ''
}

/*
* 用于删除session信息
*/
export function removeSession(name) {
  window.sessionStorage.removeItem(name)
}
export function dataHandle(res, callback) {
  if (!res) return
  if (res.status !== 0) {
    return
  }
  try {
    callback && callback()
  } catch (error) {
    console.log(error)
  }
}